import { Component, OnInit, ChangeDetectorRef, ViewChild, Inject, forwardRef } from '@angular/core';
import { ImageManagementGridComponent } from './image-management-grid/image-management-grid.component';
import { FileUploader } from '../../../../lib/ng2-file-upload';
import { path } from '../../../path.config';
import { masterService } from '../../../../lib/master.service';
import { AppComponent } from '../../../app.component';

import * as $ from 'jquery';

@Component({
    selector: 'app-image-management',
    templateUrl: './image-management.component.html',
    styleUrls: ['./image-management.component.css'],
    providers: [masterService, forwardRef(() => AppComponent)]
})

export class ImageManagementComponent implements OnInit {

    @ViewChild('imageGrid') private imageGrid: ImageManagementGridComponent;

    // 获取列表项api
    private getList = path.materialManagement.imageManagement.getImgList;

    // 添加上传的图片
    private addImgItem = path.imagesUpload.apiUrl;

    private getImgId = path.imagesUpload.getImgId;

    // 上传图片获取图片id所需传的对象
    public uploadPic = {
        imageName: '',
        imageUrl: '',
        extension: '',
        imageSize: '',
        resolution: ''
    };

    // 搜索传参的对象
    public filter: any = {
        imageName: '',
        pageSize: '10',
        pageIndex: '1'
    }

    constructor(private _masterService: masterService,
        private cdRef: ChangeDetectorRef,
        @Inject(forwardRef(() => AppComponent)) private app: AppComponent) { }

    ngOnInit() { }

    public uploader: FileUploader = new FileUploader({
        url: this.addImgItem,
        method: 'post',
        itemAlias: 'uploadedFile'
    })

    // 过滤grid数据
    public selectListItem(initType?) {
        this.imageGrid.onChangeTable(this.filter, '1');
    }

    uploadFile(thisItem) {
        let that = this;
        if (thisItem == undefined) {
            this.app.toastWarning('请上传图片！');
            return;
        } else if (!this.uploadPic.imageName) {
            this.app.toastWarning('请输入图片名称！');
            return;
        } else if (!thisItem.resolution) {
            this.app.toastWarning('请上传图片格式文件！');
            return;
        }

        thisItem.withCredentials = false;
        // 成功回调
        thisItem.onSuccess = function (response, status, headers) {
            // 上传文件成功
            if (status == 200) {
                // 上传文件后获取服务器返回的数据
                let tempRes = JSON.parse(response);
                that.uploadPic = {
                    imageName: that.uploadPic.imageName,
                    imageUrl: tempRes.data.url[0],
                    extension: thisItem.some.type.split('/')[thisItem.some.type.split('/').length - 1],
                    imageSize: thisItem.some.size + 'B',
                    resolution: thisItem.resolution
                }
                that.uploader.queue = [];
                that._masterService
                    .postData(that.getImgId, that.uploadPic)
                    .subscribe((res) => {
                        if (res.statusCode == 200) {
                            that.app.toastSuccess('添加成功！');
                            that.uploadPic.imageName = '';
                            that.filter.imageName = '';
                            $('#uploaderPic').val('');
                            that.selectListItem('1');
                        } else if (res.statusCode == 401) {
                            this.app.logOff();
                        } else {
                            that.app.toastError('错误信息: ' + res.errorMessage);
                        }
                    })
            } else {
                // 上传文件后获取服务器返回的数据错误
                that.app.toastError('错误信息: ' + response.errorMessage);
            }
        }
        thisItem.onError = function (response, status, headers) {
            // 错误回调
            that.app.toastError('错误信息: ' + response.errorMessage);
        };
        thisItem.upload(); // 开始上传
    }

    selectedFileOnChanged(event: any) {
        let $this = this;
        let thisItem = $this.uploader.queue[0] = $this.uploader.queue[$this.uploader.queue.length - 1];
        let reader = new FileReader();
        reader.readAsDataURL(thisItem.some);
        reader.onload = function (e) {
            thisItem.src = this.result as string;
            var img = new Image();
            img.src = thisItem.src;
            img.onload = function () {
                // 存图片的分辨率
                thisItem.resolution = img.width + '*' + img.height;
            }
        }
    }
}

